import React, { useLayoutEffect, useMemo, useRef, useState } from 'react'
import { getPlatform } from '@UTILS/common'
import { Text } from '@tarojs/components'
import Taro from '@tarojs/taro'
import style from '@COMPONENTS/ExpandText/index.module.scss'
const { isRN } = getPlatform()

interface Props {
  numberOfLines: number,
  lineHeight: number,
  text: string,
  expand: boolean,
  textClass: string,
  onInitCollapse: (collapse: boolean) => void
}
const ExpandTextNoBtn: React.FC<Props> = ({ numberOfLines, lineHeight, text, expand, textClass, onInitCollapse }) => {
  const ref = useRef()
  const id = useMemo(() => `id${Math.round(Math.random() * 10)}`, [])
  const isInitRef = useRef<boolean>(true)
  const [tempNumberOfLines, setTempNumberOfLines] = useState(numberOfLines + 1)
  const normalTextStyle = isRN ? {} : { '-webkit-line-clamp': 'unset', maxHeight: 'unset' }
  const moreLineTextStyle = isRN ? {} : { '-webkit-line-clamp': tempNumberOfLines.toString(), maxHeight: `${tempNumberOfLines * (lineHeight)}PX` }
  const dynamicTextStyle = expand ? normalTextStyle : moreLineTextStyle
  const lineHeightStyle = { lineHeight: `${lineHeight}PX` }
  useLayoutEffect(
    () => {
      if (!isInitRef.current) return
      const setHeightExpand = (isInit: boolean) => {
        const query = Taro.createSelectorQuery()
        query.select(`#${id}`).boundingClientRect(res => {
          let height = res?.height
          const realMaxHeight = numberOfLines * lineHeight
          if (getPlatform().isWeb) {
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-ignore
            height = height > realMaxHeight ? height : (ref.current?.offsetHeight || height)
          }
          if (height === undefined) {
            isInit && setTimeout(() => setHeightExpand(false), 100)
            return
          }
          onInitCollapse?.(height > realMaxHeight)
          setTempNumberOfLines(numberOfLines)
          isInitRef.current = false
        }).exec()
      }
      Taro.nextTick(() => {
        setHeightExpand(true)
      })
    },
    [numberOfLines, text, lineHeight, onInitCollapse, id]
  )
  return (
    <Text
      ref={ref}
      id={id}
      className={`${style.expandText} ${textClass}`}
      style={({ ...dynamicTextStyle, ...lineHeightStyle })}
    >
      {text}
    </Text>
  )
}

export default ExpandTextNoBtn
